package behaviors;

import model.Entity;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.contacts.ContactPoint;
import org.jbox2d.dynamics.contacts.ContactResult;
import org.newdawn.slick.Input;
import controller.Global;

public class Control extends Behavior {

	@Override
	public void update(Body b) {
		super.update(b);

		float force = 500.0f / Global.targetFPS;

		if (Global.input.isKeyDown(Input.KEY_LEFT)) {
			if (body.getLinearVelocity().x > -4) {
				body.applyImpulse(new Vec2(-force / 2, 0), new Vec2(body
						.getPosition().x, body.getPosition().y));
			}
			((Entity) body.getUserData()).facing = true;

		} else if (Global.input.isKeyDown(Input.KEY_RIGHT)) {
			if (body.getLinearVelocity().x < 3) {
				body.applyImpulse(new Vec2(force / 2, 0), new Vec2(body
						.getPosition().x, body.getPosition().y));
			}
			((Entity) body.getUserData()).facing = false;
		}

		if (Global.input.isKeyDown(Input.KEY_UP)
				&& !((Entity) body.getUserData()).isJumping
				&& body.getLinearVelocity().y < 3) {

			if (body.getPosition().y > Global.waterLevel) {
				((Entity) body.getUserData()).isJumping = true;
				body.applyImpulse(new Vec2(0, force * 10), new Vec2(body
						.getPosition().x, body.getPosition().y));
			} else {
				body.applyImpulse(new Vec2(0, force / 2), new Vec2(body
						.getPosition().x, body.getPosition().y));
			}

		} else if (Global.input.isKeyDown(Input.KEY_DOWN)
				&& !((Entity) body.getUserData()).isJumping
				&& body.getLinearVelocity().y > -3) {

			body.applyImpulse(new Vec2(0, -force / 2), new Vec2(body
					.getPosition().x, body.getPosition().y));
		}

		if (Global.input.isKeyDown(Input.KEY_E)) {
			if (body.getAngularVelocity() > -1f) {
				body.applyTorque(-2300f);
			}
		}

		if (Global.input.isKeyDown(Input.KEY_Q)) {
			if (body.getAngularVelocity() < 1f) {
				body.applyTorque(2300f);
			}
		}

		// create artificial friction to prevent sticking to walls
		if (body.getContactList() != null) {
			Vec2 velocity = body.getLinearVelocity();
			body
					.applyImpulse(new Vec2(-velocity.x, 0), body
							.getPosition());
		}
	}

	@Override
	public void onCollide(ContactPoint arg0) {
	}

	@Override
	public void onPersist(ContactPoint arg0) {
	}

	@Override
	public void onRemove(ContactPoint arg0) {
	}

	@Override
	public void onResult(ContactResult arg0) {
	}

	@Override
	public void init() {
	}
}
